import { AfterContentChecked, AfterContentInit, Component, OnInit, ViewChild } from '@angular/core';
import { LeftComponent } from './left/left.component';
import { CenterComponent } from './center/center.component';
import { RightComponent } from './right/right.component';
import { NzModalService } from 'ng-zorro-antd';
import { ModalComponent } from './modal/modal.component';
import { HttpService } from '@core/services/http.service';
import swal, { SweetAlertType } from 'sweetalert2';
import { TopComponent } from './top/top.component';
import { ActivatedRoute } from "@angular/router";


@Component({
    selector: 'app-scene',
    templateUrl: './scene.component.html',
    styleUrls: ['./scene.component.less']
})
export class SceneComponent implements OnInit, AfterContentChecked {
    componentType: string;
    componentToolType: string;
    canDrag = false;
    preview = false;
    styleObject = {};
    dataObject = {};
    rightStyleX;
    rightStyleY;
    rightStyleW;
    rightStyleH;
    rightData;
    node_id = [];
    n_type = '';
    gids = [];
    nextNodes = [];
    role = JSON.parse(localStorage.getItem('_user')).role;

    @ViewChild(LeftComponent) LeftComponent: LeftComponent;
    @ViewChild(CenterComponent) CenterComponent: CenterComponent;
    @ViewChild(RightComponent) RightComponent: RightComponent;
    @ViewChild(TopComponent) TopComponent: TopComponent;
    scale;

    constructor(private modal: NzModalService, public http: HttpService, private activeRoute: ActivatedRoute) {
    }

    n_id;
    g_id;
    rect = {
        width: '0',
        height: '0'
    };
    comeList = [];
    defaultComeList = [];
    pdata = { p_id: '', p_width: '', p_height: '', process_type: '' , typename: ''};
    n_name;
    logic;
    multiLogic;
    typename;
    ngOnInit() {
        this.activeRoute.queryParams.subscribe(params => {
            // 需要n_id(保存场景用);
            //
            const jsonObj = JSON.parse(params.data);

            // console.log(jsonObj);
            // 流程带来的数据
            this.n_name = jsonObj.n_name;
            this.n_id = jsonObj.n_id;
            this.g_id = jsonObj.g_id;
            this.node_id = jsonObj.nids;
            this.comeList = jsonObj.gids;
            this.n_type = jsonObj.n_type;
            this.gids = jsonObj.gids;
            this.nextNodes = jsonObj.node_id;
            this.defaultComeList = jsonObj.come_list;
            this.rect.width = jsonObj.p_width;
            this.rect.height = jsonObj.p_height;
            this.pdata.p_id = jsonObj.p_id;
            this.pdata.p_width = jsonObj.p_width;
            this.pdata.p_height = jsonObj.p_height;
            this.pdata.process_type = jsonObj.process_type;
            this.pdata.typename = jsonObj.typename;
            this.typename = jsonObj.typename;

            console.log(this.comeList);

            // 根据流程带来的节点id获取场景
            let param;
            // if (this.role == 3) {
            param = { n_id: jsonObj.n_id,p_id:this.pdata.p_id ,isCloud: jsonObj.typename };
            // } else {
            //     param = { n_id: jsonObj.n_id, isCloud: 'false' }
            // }
            this.http.getScenesById(param).subscribe(data => {
                if (data.list.length === 0) return false;
                const obj = JSON.parse(data.list[0].s_data);
                // 遍历场景内组件;
                for (const value of obj.componentList) {
                    this.CenterComponent.componentList.push(value);
                }

                // 遍历数据来源并添加check = true;
                for (const value of obj.comeList) {
                    for (let i = 0; i < this.comeList.length; i++) {
                        if (this.comeList[i].value === value) {
                            this.comeList[i].checked = true;
                        }
                    }
                }
                // 编辑好的逻辑数组经center传入其内部的logic组件
                this.logic = obj.logic;
                this.multiLogic = obj.multiLogic;

            });

        });
    }

    // 方便添加用

    // 数据来源


    addCome() {
        this.comeList.push({
            value: '',
            label: ''
        });
    }


    colmulate = false;

    ngAfterContentChecked() {
        if (this.colmulate) return false;
        const w = this.CenterComponent.el.nativeElement.offsetWidth;
        const h = this.CenterComponent.el.nativeElement.offsetHeight;
        let scale = null;
        if (w !== 0 && !scale) {
            this.colmulate = true;
            const wc = w / (+this.rect.width);
            const hc = h / (+this.rect.height);
            scale = wc < hc ? wc : hc;
            this.TopComponent.scaleOption.push({
                value: scale, label: '最佳比例'
            });
        }

    }

    dragStart($event) {
        this.componentType = $event.componentType;
        this.canDrag = true;
    }

    dropend($event) {
        this.componentToolType = $event.componentToolType;
        this.rightStyleX = $event.rightStyleX;
        this.rightStyleY = $event.rightStyleY;
        this.rightStyleW = $event.rightStyleW;
        this.rightStyleH = $event.rightStyleH;
        this.rightData = $event.rightData;
    }

    onMove($event) {
        this.rightStyleX = $event.rightStyleX;
        this.rightStyleY = $event.rightStyleY;
    }

    onResize($event) {
        this.rightStyleW = $event.rightStyleW;
        this.rightStyleH = $event.rightStyleH;
    }

    onToggleEvent($event) {
        this.componentToolType = $event.componentToolType;
        this.rightStyleX = $event.rightStyleX;
        this.rightStyleY = $event.rightStyleY;
        this.rightStyleW = $event.rightStyleW;
        this.rightStyleH = $event.rightStyleH;
        this.rightData = $event.rightData;
    }

    onDrop() {
        this.canDrag = false;
    }

    onTopChange($event) {
        this.styleObject = $event;
    }

    onToolChange($event) {
        this.styleObject = $event;
    }

    onToolChangeTxt($event) {
        this.dataObject = $event;
        // console.log(this.dataObject)
    }

    sort($event) {
        if (this.CenterComponent.componentList.length === 0) {
            return false;
        }
        switch ($event) {
            case 'top':
                this.top();
                break;
            case 'bottom':
                this.bottom();
                break;
            case 1:
                this.moveOne(1);
                break;
            case -1:
                this.moveOne(-1);
                break;
        }
    }

    top() {
        const currentId = this.CenterComponent.currentId;
        if (currentId === this.CenterComponent.componentList.length - 1) return false;
        const componentList = this.CenterComponent.componentList;
        const length = this.CenterComponent.componentList.length;
        const tmp = componentList.splice(currentId, 1);
        componentList.push(tmp[0]);
        this.CenterComponent.currentId = length - 1;
    }

    bottom() {
        const currentId = this.CenterComponent.currentId;
        if (currentId === 0) return false;
        const componentList = this.CenterComponent.componentList;
        const tmp = componentList.splice(currentId, 1);
        componentList.unshift(tmp[0]);
        this.CenterComponent.currentId = 0;
    }

    moveOne(index) {
        if ((this.CenterComponent.currentId === this.CenterComponent.componentList.length - 1 && index === 1)
            || (this.CenterComponent.currentId === 0 && index === -1)) return false;
        const currentId = this.CenterComponent.currentId;
        const componentList = this.CenterComponent.componentList;
        const tmp = componentList[currentId + index];
        componentList[currentId + index] = componentList[currentId];
        componentList[currentId] = tmp;
        this.CenterComponent.currentId = currentId + index;
    }

    onDelete() {
        this.CenterComponent.componentList.splice(this.CenterComponent.currentId, 1);
    }

    changeScale($event) {
        this.scale = $event.scale;
    }

    onPreview() {
        const options = {
            wrapClassName: 'fill-screen',
            content: ModalComponent,
            footer: false,
            componentParams: {
                componentList: this.CenterComponent.componentList,
                style: {
                    width: this.rect.width,
                    height: this.rect.height
                }
            }
        };
        this.modal.open(options).subscribe(result => {

        });
    }

    comeListCheck = [];

    finalSave() {

        if(this.CenterComponent.componentList[0]){
            if (this.CenterComponent.componentList[0].name == 'SG_infoext') {
                console.log(this.CenterComponent.componentList[0])
                if (!this.CenterComponent.componentList[0].choose_n_id.length) {
                    swal('请选择节点', '', 'info');
                    return;
                }
            }
        }
        if (this.CenterComponent.LogicComponent.allLogicData.length === 0) {
            this.CenterComponent.LogicComponent.saveAllLogic.emit([{
                logicType: 'default',
                rules: [],
                target: this.CenterComponent.LogicComponent.target.value || ''
            }]);
        } else {
            this.CenterComponent.LogicComponent.saveAllLogic.emit(this.CenterComponent.LogicComponent.allLogicData);
        }

        if (this.CenterComponent.LogicComponent.multiLogicData.length === 0) {
            this.CenterComponent.LogicComponent.saveAllMultiLogic.emit([]);
        } else {
            this.CenterComponent.LogicComponent.saveAllMultiLogic.emit([{
                logicType: this.CenterComponent.LogicComponent.multiLogicType,
                rules: this.CenterComponent.LogicComponent.multiLogicData
            }]);
        }


        if (this.CenterComponent.componentList) {
            for (let comp of this.CenterComponent.componentList) {
                if (!comp.style.x) {
                    comp.style.x = 0
                }
                if (!comp.style.y) {
                    comp.style.y = 0
                }
            }
        }

        if (this.node_id.length == 1 && this.CenterComponent.logic.length == 0) {
            this.CenterComponent.logic.push({
                logicType: 'default',
                rules: [],
                target: this.node_id[0].value
            })
        }



        const comObj = {
            n_id: this.n_id,
            g_id: this.g_id,
            p_id: this.pdata.p_id,
            s_data: {
                componentList: this.CenterComponent.componentList,
                logic: this.CenterComponent.logic,
                multiLogic: this.CenterComponent.multiLogic,
                comeList: this.defaultComeList,
                name: this.n_name,
                n_id: this.n_id,
                g_id: this.g_id,
                p_id: this.pdata.p_id
            }
        };

        // 遍历组件内被选择的数据来源数组，被选中的添加至comeList;
        // this.comeListCheck.length = 0;
        // let bool = false;
        // for (const data of this.comeList) {
        //     if (data['checked'] === true && this.n_type !== 'empty') {
        //         bool = true;
        //         this.comeListCheck.push(
        //             data.value
        //         );
        //     }
        // }
        // if (bool) {
        //     comObj.s_data.comeList = this.comeListCheck;
        // }

        // if (this.role == 3) {
            comObj['isCloud'] = this.typename;
        // } else {
        //     comObj['isCloud'] = 'false';
        // }
        this.http.addScenes(comObj).subscribe(res => {
            swal(`${res['msg']}`, '', 'info');
        });
    }

}
